﻿using System;
using System.Collections.Generic;
using System.Text;
using Pixysoft.Framework.Noebe;
using System.Data;

namespace Pixysoft.Framework.Security.Tokens
{
    class TokenUserInfoController : ITokenUserInfoDesigner
    {
        private static volatile TokenUserInfoController instance;

        private static object syncRoot = new Object();

        public static TokenUserInfoController Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new TokenUserInfoController();
                        }
                    }
                }
                return instance;
            }
        }


        /// <summary>
        /// 查看是否有用户列表
        /// </summary>
        /// <returns></returns>
        internal bool HasProfile()
        {
            INoebeCommand command = TokenHelper.Instance.GetNoebeManager().NoebeCommand;
            command.SQL = "SELECT COUNT(*) FROM SEC_TOKEN_USERPROFILE";
            DataTable table = command.ExecuteReader();

            try
            {
                return int.Parse(table.Rows[0][0].ToString()) > 0;
            }
            catch (Exception ex)
            {
                LoggerHelper.Error(ex.ToString());

                return true;
            }
        }

        /// <summary>
        /// 用户名对应的用户是否存在
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public bool HasProfile(string username)
        {
            if (string.IsNullOrEmpty(username))
                return false;

            username = username.Trim().ToUpper();

            INoebeCommand command = TokenHelper.Instance.GetNoebeManager().NoebeCommand;

            command.SQL = "SELECT COUNT(*) FROM SEC_TOKEN_USERPROFILE WHERE USERNAME = :USERNAME";

            command.Parameters.Add("USERNAME", username);

            try
            {
                return int.Parse(command.ExecuteReader().Rows[0][0].ToString()) > 0;
            }
            catch (Exception ex)
            {
                LoggerHelper.Error("error when has userprofile." + username);

                LoggerHelper.Error(ex.ToString());

                return false;
            }
        }

        /// <summary>
        /// 用户名 密码 对应的用户是否存在
        /// </summary>
        /// <param name="username"></param>
        /// <param name="md5password"></param>
        /// <returns></returns>
        public bool HasProfile(string username, string md5password)
        {
            if (string.IsNullOrEmpty(username))
                return false;

            username = username.Trim().ToUpper();

            INoebeCommand command = TokenHelper.Instance.GetNoebeManager().NoebeCommand;

            command.SQL = "SELECT COUNT(*) FROM SEC_TOKEN_USERPROFILE WHERE USERNAME = :USERNAME AND USERPASSWORD = :USERPASSWORD";

            command.Parameters.Add("USERNAME", username);

            command.Parameters.Add("USERPASSWORD", md5password);

            try
            {
                return int.Parse(command.ExecuteReader().Rows[0][0].ToString()) > 0;
            }
            catch (Exception ex)
            {
                LoggerHelper.Error("error when has userprofile." + username);

                LoggerHelper.Error(ex.ToString());

                return false;
            }
        }


        /// <summary>
        /// 获取用户信息列表
        /// </summary>
        /// <param name="username"></param>
        /// <param name="md5password"></param>
        /// <returns></returns>
        public DataTable GetProfile()
        {
            INoebeCommand command = TokenHelper.Instance.GetNoebeManager().NoebeCommand;

            command.SQL = "SELECT * FROM SEC_TOKEN_USERPROFILE";

            DataTable table = command.ExecuteReader();

            return table;
        }

        /// <summary>
        /// 获取用户信息列表
        /// </summary>
        /// <param name="username"></param>
        /// <param name="md5password"></param>
        /// <returns></returns>
        public DataRow GetProfile(string username, string md5password)
        {
            if (string.IsNullOrEmpty(username))
                return null;

            username = username.Trim().ToUpper();

            if (string.IsNullOrEmpty(md5password))
                return null;


            INoebeCommand command = TokenHelper.Instance.GetNoebeManager().NoebeCommand;

            command.SQL = "SELECT * FROM SEC_TOKEN_USERPROFILE WHERE USERNAME = :USERNAME AND USERPASSWORD = :USERPASSWORD";

            command.Parameters.Add("USERNAME", username);

            command.Parameters.Add("USERPASSWORD", md5password);

            DataTable table = command.ExecuteReader();

            if (table.Rows.Count == 0)
                return null;

            return table.Rows[0];
        }

        /// <summary>
        /// 注册一个用户
        /// </summary>
        /// <param name="username"></param>
        /// <param name="md5password"></param>
        /// <returns></returns>
        public bool Register(string username, string md5password)
        {
            if (string.IsNullOrEmpty(username))
                return false;

            username = username.Trim().ToUpper();

            if (string.IsNullOrEmpty(md5password))
                return false;

            if (HasProfile(username))
                return false;

            DataTable table = TokenHelper.Instance.GetNoebeManager().GetEntity("SEC_TOKEN_USERPROFILE");
            DataRow row = table.NewRow();
            row["USERCODE"] = TokenHelper.GeneratePrimaryKey();
            row["USERNAME"] = username;
            row["USERPASSWORD"] = md5password;
            row["STATUS"] = TokenStatus.Available;
            row["ISSUPERUSER"] = false;
            row["CREATEDATE"] = TokenHelper.DateTimeNow;
            row["MODIDATE"] = TokenHelper.DateTimeNow;
            table.Rows.Add(row);

            TokenHelper.Instance.GetNoebeManager().Session.Insert(table);

            return true;
        }

        /// <summary>
        /// 删除一个用户
        /// </summary>
        /// <param name="username"></param>
        /// <param name="md5password"></param>
        /// <returns></returns>
        public bool Cancellation(string username, string md5password)
        {
            if (string.IsNullOrEmpty(username))
                return false;

            username = username.Trim().ToUpper();

            if (string.IsNullOrEmpty(md5password))
                return false;

            INoebeCommand command = TokenHelper.Instance.GetNoebeManager().NoebeCommand;

            command.SQL = "DELETE FROM SEC_TOKEN_USERPROFILE WHERE USERNAME = :USERNAME AND USERPASSWORD = :USERPASSWORD";

            command.Parameters.Add("USERNAME", username);

            command.Parameters.Add("USERPASSWORD", md5password);

            return command.Execute() > 0;
        }


        /// <summary>
        /// 删除所有的token数据和用户数据
        /// </summary>
        internal void ShutDown()
        {
            //删除所有的用户数据

            INoebeCommand command = TokenHelper.Instance.GetNoebeManager().NoebeCommand;
            command.SQL = "DELETE FROM SEC_TOKEN_USERPROFILE";
            command.Execute();
        }

        /// <summary>
        /// 添加一个默认用户
        /// </summary>
        internal void Restart()
        {
            DataTable table = TokenHelper.Instance.GetNoebeManager().GetEntity("SEC_TOKEN_USERPROFILE");
            DataRow row = table.NewRow();
            row["USERCODE"] = TokenHelper.GeneratePrimaryKey();
            row["USERNAME"] = TokenHelper.default_username;
            row["USERPASSWORD"] = TokenHelper.default_password;
            row["STATUS"] = TokenStatus.Available;
            row["ISSUPERUSER"] = true;
            row["CREATEDATE"] = TokenHelper.DateTimeNow;
            row["MODIDATE"] = TokenHelper.DateTimeNow;
            table.Rows.Add(row);

            TokenHelper.Instance.GetNoebeManager().Session.Insert(table);

        }

        /// <summary>
        /// 读取用户列表加载
        /// </summary>
        internal void Reload()
        {
            try
            {
                List<TokenUserInfo> list = Pixysoft.IO.XmlImporter.Instance.XmlImport<
                    List<TokenUserInfo>>(AppDomain.CurrentDomain.BaseDirectory + @"\" +
                TokenHelper.default_reloadfilename);

                foreach (TokenUserInfo profile in list)
                {
                    Register(profile.Name.Trim().ToUpper(), profile.Md5Password);
                }
            }
            catch (Exception ex)
            {
            }
        }
    }
}
